package com.open.capacity.finance.service.impl;

import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.finance.util.POIExcelUtil;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.service.SysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.finance.entity.SourceBaseFinalaccountTotal4;
import com.open.capacity.finance.dao.SourceBaseFinalaccountTotal4Dao;
import com.open.capacity.finance.service.SourceBaseFinalaccountTotal4Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class SourceBaseFinalaccountTotal4ServiceImpl implements SourceBaseFinalaccountTotal4Service {

    @Autowired
    private SourceBaseFinalaccountTotal4Dao sourceBaseFinalaccountTotal4Dao;

    @Autowired
    private SysCompanyService companyService;

    /**
     * 保存到数据库
     *
     * @param url
     */
    @Transactional
    public int save2db(String companyId, Integer kjnd, Integer importway, String url) {
        MultipartFile multipartFile = FileUtil.toMultipartFile("finalaccountXls", url);
        InputStream inputStream = null;
        Workbook wb = null;
        try {
            inputStream = multipartFile.getInputStream();
            wb = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            log.error("save2db error:" + e.getMessage());
        }
        Sheet sheet = null;
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            if (wb.getSheetName(i).contains("F04 非税收入征缴情况表")) {
                sheet = wb.getSheetAt(i);
                break;
            }
        }

        if (sheet == null) {
            return -1;
        }

        // 获取最大行数(或者sheet.getLastRowNum())
        int rownum = sheet.getPhysicalNumberOfRows();

        Row row = sheet.getRow(7);
        Assert.notNull(row, "数据格式不合法");
        List<SourceBaseFinalaccountTotal4> list = new ArrayList<>();
        SysCompany company = companyService.findById(companyId);
        // 处理行数据
        for (int i = row.getRowNum(); i < rownum; i++) {
            row = sheet.getRow(i);
            // 遇到空行则结束
            if (row == null || row.getCell(0) == null) {
                break;
            }

            String kjkmcode = row.getCell(0).getStringCellValue();
            String kjkmname = row.getCell(4).getStringCellValue();
            if (StringUtils.isEmpty(kjkmname)) {
                break;
            }
            BigDecimal totalAmount = POIExcelUtil.getNumber(row.getCell(7));
            BigDecimal selfAmount = POIExcelUtil.getNumber(row.getCell(8));
            BigDecimal unselfAmount = POIExcelUtil.getNumber(row.getCell(9));

            SourceBaseFinalaccountTotal4 item = new SourceBaseFinalaccountTotal4();
            item.setCompanyId(companyId);
            item.setCompanyName(company.getFullName());
            item.setKjnd(kjnd);
            item.setKjkmCode(kjkmcode.trim());
            item.setKjkmName(kjkmname.trim());
            item.setTotalMoney(totalAmount);
            item.setSelfMoney(selfAmount);
            item.setUnselfMoney(unselfAmount);

            list.add(item);
        }

        //删除旧数据
        if (importway == 1) {
            delete(companyId, kjnd);
        }

        for (SourceBaseFinalaccountTotal4 item : list) {
            item.setCompanyId(companyId);
            item.setKjnd(kjnd);
            sourceBaseFinalaccountTotal4Dao.save(item);
        }

        return list.size();
    }

    /**
     * 删除
     *
     * @param companyId
     */
    public int delete(String companyId, Integer kjnd) {
        return sourceBaseFinalaccountTotal4Dao.deleteByCompanyIdAndKjnd(companyId, kjnd);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SourceBaseFinalaccountTotal4 findById(String id) {
        return sourceBaseFinalaccountTotal4Dao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SourceBaseFinalaccountTotal4> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SourceBaseFinalaccountTotal4> list = sourceBaseFinalaccountTotal4Dao.findAll(params);
        PageInfo<SourceBaseFinalaccountTotal4> pageInfo = new PageInfo(list);

        return PageResult.<SourceBaseFinalaccountTotal4>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SourceBaseFinalaccountTotal4> findAll(Map<String, Object> params) {
        return sourceBaseFinalaccountTotal4Dao.findAll(params);
    }

}
